<template>
    <view class='container'>
        <card-box :articleId='articleId' :isAlreadySubmission='isAlreadySubmission' :index='index' :total='total'
            :currentQuestion='currentQuestion' @next='next' @restart='restart' @submit='submit'>
            <template v-slot:question>
                <view class="question-box">
                    <view v-for='(pItem, pIndex) in clozeData' :key="pIndex" :id='"p-"+pIndex'
                        :class='[getItemClass(pItem,answer)]'>
                        <text v-for='(sItem, sIndex) in pItem.childs' :key='sIndex' :id='"s-"+sItem.markIndex'
                            :class="[getItemClass(sItem,answer)]" @click.stop='tapItem(sItem)'>
                            {{sItem.content}}
                        </text>
                    </view>
                </view>
            </template>
            <template v-slot:answer>
                <view class="answer-box c-flex_row c-flex_warp">
                    <view class="answer-item c-flex_row" v-for='(item, index) in answer' :key='index'
                        @click="tapAnswer(index)">
                        <view class="title">
                            NO.{{index+1}}
                        </view>
                        <view class="answer c-flex_1" :class='{"empty-answer": !item.answer}'>
                            {{item.answer ? item.answer : "尚未回答"}}
                        </view>
                    </view>
                </view>
                <card-result :isAlreadySubmission='isAlreadySubmission' :isCorrect='isCorrect'></card-result>
                <cloze-answer-pop ref='answerPop' @confirm='confirmAnswer'></cloze-answer-pop>
            </template>
        </card-box>
    </view>
</template>

<script>
    import TestCardMixin from "../mixins/test-card-mixin.js";
    import CardBox from "./card-box.vue";
    import ClozeAnswerPop from "./cloze-answer-pop.vue";
    import CardResult from "./card-result.vue";
    import {
        isEmpty
    } from "../../../../../common/utils/util.js"
    import {
        submitClozeAnswer
    } from "../../../services/index.js"
    export default {
        components: {
            CardBox,
            ClozeAnswerPop,
            CardResult
        },
        mixins: [TestCardMixin],
        data: function() {
            return {
                isAlreadySubmission: false,
                clozeData: null,
                answer: null,
                score: 0,
                isCorrect: false
            }
        },
        watch: {
            currentQuestion: {
                handler: function(n) {
                    if (n) {
                        this.isAlreadySubmission = false;
                        this.getClozeAndAnswerData(n, this.answer);
                    } else {
                        this.clozeData = null;
                        this.answer = null;
                    }
                },
                immediate: true
            }
        },
        methods: {
            tapAnswer(index) {
                uni.pageScrollTo({
                    selector: `.container >>> .mark-${index}`
                })
            },
            // 点击文章
            tapItem(item) {
                // 显示输入框
                if (item.isMark) {
                    let ref = this.$refs.answerPop;
                    if (ref) {
                        ref.showAnswerPop(true, this.answer[item.markIndex]);
                    }
                }
            },
            // 获取item class
            getItemClass(item, answerList) {
                let result = item.tag.split(" ");
                if (result.indexOf("p") != -1) {
                    result.push("section") // 段落
                } else if (result.indexOf("mark") != -1) {
                    result.push(`mark-${item.markIndex}`) // 用于定位
                    answerList.forEach((aItem, aIndex) => {
                        if (item.markIndex == aItem.index) {
                            if (aItem.answer) {
                                result.push("answered") // 已经回答
                            }
                        }
                    })
                }
                return result;
            },
            // 文章数据处理
            handlerClozeData(question, answer) {
                let details = question.subject;
                // 用于初始化answer数据
                let markIndex = 0;
                let markResult = answer ? answer : [];
                let needInitAnswer = isEmpty(markResult); // 如果answer 为空，就需要初始化answer
                // 文章数据处理结果
                let result = [];
                details = details.replace(/\n/g, "");
                details = details.replace(/\s+/g, " ");
                let pList = details.match(/<p>().*?<\/p>/imgs).filter(item => {
                    return item != ""
                });
                pList = pList.map(item => {
                    item = item.replace(/<\/?p>/g, "");
                    item = item.replace(/<br\/>/g, "\n");
                    item = item.replace(/<br \/>/g, "\n")
                    return item;
                });
                // 遍历段落
                pList.forEach((pItem, pIndex) => {
                    // 根据mark标签，拆分段落
                    let splitByMarkTag = (pItem) => {
                        let list = pItem.split(/<mark>().*?<\/mark>/imgs).filter(item => {
                            return item != ""
                        });
                        let splitResult = [];
                        // 遍历拆分结果，生成文章语句列表
                        list.forEach((sItem, sIndex) => {
                            // 添加正常文本
                            splitResult.push({
                                tag: "text",
                                content: sItem,
                            })
                            // 因为各文本由mark标签区分，所以需要回写插入mark标签，除了最后一个
                            if (sIndex != list.length - 1) {
                                // 如果需要初始化答题结果列表，markResult 插入数据
                                if (needInitAnswer) {
                                    markResult.push({
                                        answer: undefined,
                                        index: markIndex
                                    })
                                }
                                let mark = markResult[markIndex];
                                splitResult.push({
                                    tag: "mark",
                                    content: mark.answer ? mark.answer :
                                        `Question-NO.${markIndex+1}`,
                                    isMark: true,
                                    markIndex,
                                    pIndex,
                                    index: sIndex
                                })
                                markIndex++;
                            }
                        })
                        return splitResult;
                    }
                    result.push({
                        tag: "p",
                        childs: splitByMarkTag(pItem),
                        index: pIndex
                    })
                })
                return {
                    clozeResult: result,
                    answerResult: markResult
                };
            },
            next: function() {
                this.$emit("next", {
                    finish: this.finish
                })
            },
            submit: function() {
                let result = this.answer.filter(item => {
                    return item.answer
                });

                if (result.length == this.answer.length) {
                    uni.showLoading({
                        title: "提交中",
                    })
                    submitClozeAnswer(this.articleId, this.answer.map(item => {
                        return item.answer
                    }), this.currentQuestion.id).then(
                        res => {
                            this.score = res.score;
                            this.isCorrect = res.isCorrect;
                            this.isAlreadySubmission = true;
                        }).finally(() => {
                        uni.hideLoading()
                    })
                } else {
                    uni.showToast({
                        title: "有未填内容",
                        icon: 'none'
                    })
                }
            },
            restart: function() {
                this.score = 0;
                this.isCorrect = 0;
                this.isAlreadySubmission = false;
                this.answer = null;
                this.getClozeAndAnswerData(this.currentQuestion, this.answer);
            },
            confirmAnswer: function(e) {
                this.$set(this.answer, e.answer.index, e.answer);
                const tempAnswer = this.answer;
                tempAnswer[e.answer.index] = e.answer;
                this.getClozeAndAnswerData(this.currentQuestion, tempAnswer);
            },
            getClozeAndAnswerData(currentQuestion, answer) {
                let result = this.handlerClozeData(currentQuestion, answer);
                this.clozeData = result.clozeResult;
                this.answer = result.answerResult;
                this.$forceUpdate();
            }
        }
    }
</script>

<style lang="scss" scoped>
    .question-box {
        --h1_font_size: 40rpx;
        --p_font_size: 36rpx;
        --text_font_size: 36rpx;
        --point_font_size: 36rpx;

        --h1_color: #333;
        --p_color: #333;
        --text_color: #333;
        --point_color: #9470e0;

        word-wrap: normal;
        word-break: normal;

        .h1 {
            font-size: var(--h1_font_size);
            color: var(--h1_color);
            font-weight: 800;
        }

        .p {
            font-size: var(--p_font_size);
            color: var(--p_color);
        }

        .section {
            margin-bottom: 30rpx;
            margin-top: 0;
            display: inline-block;
            line-height: 1.7em;
        }

        .text {
            font-size: var(--text_font_size);
            color: var(--text_color);
            font-weight: 400;
        }

        .mark {
            background: transparent;
            padding: 0 0.6em;
            margin: 0 0.2em;

            color: #c8c8c8;
            border: 4rpx solid #ff6d2a;
            font-size: 30rpx;
            font-weight: 400;

            word-wrap: normal;
            word-break: normal;
            white-space: nowrap;

            border-radius: 10rpx;
        }

        .answered {
            background: #cefffb;

            color: var(--point_color);
            border: 4rpx solid transparent;
            font-size: var(--point_font_size);
            font-weight: 700;

            word-wrap: normal;
            word-break: normal;
        }
    }

    .answer-box {
        margin-left: 10rpx;

        .answer-item {
            margin-right: 20rpx;
            margin-bottom: 20rpx;
            width: calc(50% - 40rpx);

            .title {
                font-size: 34rpx;
                font-weight: 700;
                color: #333;
                margin-right: 15rpx;
            }

            .answer {
                word-wrap: break-word;
                word-break: break-all;
                white-space: normal;
                font-size: 34rpx;
                padding: 8rpx 15rpx;
                border-radius: 15rpx;
                background: #d2fddd;
                color: #333;
                border: 3rpx solid #31ed50;
            }

            .empty-answer {
                background: #ffeae6;
                color: #ff4747;
                border: 3rpx solid #ff4747;
            }
        }
    }
</style>